<?php
/**
 * Created by 张富琼 <zfuqiong@ifreegroup.com>.
 * User: kingzcheung
 * Date: 17-10-10
 * Time: 下午4:41
 */


namespace kingzcheung\migration;


class Lock {


    private static $lockFile = ROOT_PATH . 'migration/sql' . DS . 'run.lock';

    /**
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    public static function read() {
        foreach (self::getLines() as $line) {
            var_dump($line);
        }
    }

    /**
     * 获取所有已迁移文件列表
     *
     * @return array
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    public static function all() {
        $file = file(self::$lockFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        return array_map(function ($value) {
            $valueArr = explode('|', $value);

            return [
                'file' => $valueArr[0],
                'date' => $valueArr[1],
            ];
        }, $file);
    }

    /**
     * @param $data array|string 文件名+时间的数组
     * @return bool
     * @throws \Exception
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    public static function push($data) {
        if (is_string($data) && strpos($data, '|') === false) {
            throw new \Exception('数据错误');
        }
        if (is_array($data)) {
            if (sizeof($data) !== 2) {
                throw new \Exception('数组不正确');
            }

            $data = implode('|', $data);

        }

        $data .= PHP_EOL;

        return false !== file_put_contents(self::$lockFile, $data, FILE_APPEND);
    }

    /**
     * 逐行生成器
     *
     * @return \Generator
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    private static function getLines() {
        $file = fopen(self::$lockFile, 'r');
        while (!feof($file)) {
            yield explode('|', fgets($file));
        }
        fclose($file);
    }
}